//
//  PhotoBrowserCell.m
//  XinLang_OC
//
//  Created by WONG on 16/6/11.
//  Copyright © 2016年 cheuhui. All rights reserved.
//

#import "PhotoBrowserCell.h"
#import "imageView.h"
#import "UIImage+GIF.h"

#define ScreenHeight [UIScreen mainScreen].bounds.size.height
#define ScreenWidth [UIScreen mainScreen].bounds.size.width

@interface PhotoBrowserCell ()<UIScrollViewDelegate>

@property(nonatomic,strong) UIScrollView *scrollView;



@end

@implementation PhotoBrowserCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self prepareUI];
        
        self.scrollView.delegate = self;
        
        // 设置最大和最小缩放比例
        self.scrollView.maximumZoomScale = 2;
        self.scrollView.minimumZoomScale = 0.5;
    }
    return self;
}

- (void)prepareUI {
    [self.contentView addSubview:self.scrollView];
    [self.scrollView addSubview:self.imageView];
    
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[sv]-0-|" options:0 metrics:nil views:@{@"sv": self.scrollView}]];
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[sv]-0-|" options:0 metrics:nil views:@{@"sv": self.scrollView}]];
}


- (void)setUrl:(NSURL *)url {
    _url = url;
    
    if (!_url) {
        NSLog(@"url没有值");
        return;
    }
    
    self.imageView.image = nil;
    self.scrollView.contentOffset = CGPointZero;
    self.scrollView.contentSize = CGSizeZero;
    self.scrollView.contentInset = UIEdgeInsetsZero;
    self.imageView.transform = CGAffineTransformIdentity;
    
    [[SDWebImageManager sharedManager] downloadImageWithURL:url options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        float progress = receivedSize / expectedSize;
        if (self.delegate != nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showProgress:progress];
            });
        }else {
            // 退出控制器,还在下载,退出的时候就不要去下载了。
            // 取消所有下载
            [[SDWebImageManager sharedManager] cancelAll];
            [SVProgressHUD dismiss];
        }
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        [SVProgressHUD dismiss];
        
        if (error != nil) {
            [SVProgressHUD showErrorWithStatus:@"下载图片失败"];
            return;
        }
        
        // 判断是否是gif图片
        BOOL isGif = [[[url absoluteString] lowercaseString] hasSuffix:@"gif"];
        
        // 不是GIF
        if (!isGif) {
            self.imageView.image = image;
            // 重新布局 将图片等比缩放到宽度等于屏幕的宽度
            [self layoutImageView:image];
        }else { // 是GIF
            // 是gif
            // 去本地缓存查找下载好的gif图片
            // 获取到SDWebImage保存的图片名称, 将url地址,进行MD5转换成图片的名称
            NSString *imageName = [[SDWebImageManager sharedManager] cacheKeyForURL:imageURL];
            // 获得完整的图片路径
            NSString *path = [[[SDWebImageManager sharedManager] imageCache] defaultCachePathForKey:imageName];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                NSData *data = [NSData dataWithContentsOfFile:path];
                self.imageView.image = [UIImage sd_animatedGIFWithData:data];
                // 重新布局 将图片等比缩放到宽度等于屏幕的宽度
                [self layoutImageView:self.imageView.image];
            });
        }
    }];
}

/*
 将图片等比缩放到宽度等于屏幕的宽度
 长图: 高度大于屏幕的高度
 短图: 高度小于屏幕的高度
 */
- (void)layoutImageView:(UIImage *)image {
    // 将图片等比缩放到宽度等于屏幕的宽度
    CGSize size = [self displaySize:image];
    
    // 判断是长图还是短图
    // 长图:从左上角开始显示.可以滚动
    // 短图:高度方向居中显示
    if (size.height < ScreenHeight) {
        // 短图：高度方向居中显示
        CGFloat offsetY = (ScreenHeight - size.height) * 0.5;
        self.imageView.frame = CGRectMake(0, 0, size.width, size.height);
        self.scrollView.contentInset = UIEdgeInsetsMake(offsetY, 0, offsetY, 0);
    }else {
        self.imageView.frame = CGRectMake(0, 0, size.width, size.height);
        self.scrollView.contentSize = size;
    }
    
}

// 将图片等比缩放到宽度等于屏幕的宽度
- (CGSize)displaySize:(UIImage *)image {
    // 新的高度 / 新的宽度 = 旧的高度 / 旧的宽度
    // 新的高度 = 新的宽度(屏幕的宽度) * 旧的高度 / 旧的宽度
    CGFloat newWidth = ScreenWidth;
    CGFloat newHeight = newWidth * image.size.height / image.size.width;
    
    return CGSizeMake(newWidth, newHeight);
}


#pragma mark - UIScrollViewDelegate

// 告诉scrollView要缩放哪个view(缩放其实是修改这个view的transform)
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.imageView;
}

/// 当图片缩放比例小于最小缩放比例松手时,不会立马调用scrollViewDidEndZooming,回先自动缩放到最小缩放比例
/// 不让系统缩放到比设置的缩放比例还小的值
/// 每当我们缩放一点点都会来调用
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    // 让控制器给返回一个view我们来设置alpha值,实时改变控制器的背景
    if ([self.delegate respondsToSelector:@selector(viewForTransparent)]) {
        UIView *bkgView = [self.delegate viewForTransparent];
        
        // 缩放比例小于1,设置透明的
        if (self.imageView.transform.a < 1) {
            bkgView.alpha = self.imageView.transform.a * 0.7 - 0.1;

        }else {
            // 缩放比例大于1,设置alpha为1
            bkgView.alpha = 1;
        }
    }
}

/// 缩放结束的时候调用
/// 注意.建议使用frame, frame在缩放的时候是一直变化的, bounds在缩放的时候是一直不变的
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale {
    // 监听imageView的缩放,是否到了可以关闭控制器的状态
    if (self.imageView.transform.a < 0.7) {
        // 关闭控制器,cell不能关闭控制器,通过代理,告诉控制器现在可以关闭了
        // 不能直接这样关闭,直接关闭,转场动画时拿到的imageView的frame和显示的是不一样的,会先跳到左上角在转场动画到指定位置
        //            delegate?.photoBrowserCellDismissController()
        
        
        // 移动到缩略图的位置
        if ([self.delegate respondsToSelector:@selector(photoBrowserCellDismissTargetRect)]) {
            CGRect rect = [self.delegate photoBrowserCellDismissTargetRect];
            
            // 设置imageView的模式
            self.imageView.contentMode = UIViewContentModeScaleAspectFill;
            self.imageView.clipsToBounds = true;
            
            [UIView animateWithDuration:0.25 animations:^{
                self.imageView.frame = CGRectMake(0, 0, rect.size.width, rect.size.height);
                self.scrollView.contentInset = UIEdgeInsetsMake(rect.origin.y, rect.origin.x, 0, 0);
                
                // 设置contentOffest.y,长图时y值对不上.发现contentOffestY有问题
                CGPoint point = self.scrollView.contentOffset;
                point.y = -rect.origin.y;
                point.x = -rect.origin.x;
                self.scrollView.contentOffset = point;
                
            } completion:^(BOOL finished) {
                // 关闭控制器
                if ([self.delegate respondsToSelector:@selector(photoBrowserCellDismissController)]) {
                    [self.delegate photoBrowserCellDismissController];
                }
                
            }];
        }
        return;
    }else {
        // 移动到中间
        CGFloat offestX = (ScreenWidth - self.imageView.frame.size.width) * 0.5;
        CGFloat offestY = (ScreenHeight - self.imageView.frame.size.height) * 0.5;
        
        // // 当 offestX,offestY小于0回到屏幕外面去。
        if (offestX < 0) {
            offestX = 0;
        }
        if (offestY < 0) {
            offestY = 0;
        }
        // 动画
        [UIView animateWithDuration:0.25 animations:^{
            
            // 通过scrollView ContentInset
            self.scrollView.contentInset = UIEdgeInsetsMake(offestY, offestX, 0, 0);
        }];
    }
}


#pragma mark - lazy laod

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
    }
    return _scrollView;
}

- (ImageView *)imageView {
    if (!_imageView) {
        _imageView = [[ImageView alloc] init];
    }
    return _imageView;
}

@end












